<template>
  <div class="user-list-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">正在加载...</div>

    <!-- 用户卡片列表 -->
    <div v-else class="card-container">
      <el-card
          v-for="user in paginatedUsers"
          :key="user.userId"
          class="user-card"
          shadow="hover"
          @click="handlerClick(user.userId)"
      >
        <div class="card-content">
          <div class="real-name">
            <strong>用户名:</strong> {{ user.username }}
          </div>
          <div class="real-name">
            <strong>真实姓名:</strong> {{ user.userRealName }}
          </div>
          <div class="real-name">
            <strong>性别:</strong> {{ user.gender === 0 ? '男' : '女' }}
          </div>
          <div class="other-field">
            <strong>手机号:</strong> {{ user.phone }}
          </div>
          <!-- 其他需要展示的字段 -->
        </div>
      </el-card>
      <el-dialog title="聊天记录" v-model="dialogVisible" width="50%">
        <Chat :chatData="{doctorId: doctorId, userId: userId}" :key="refreshKey"/>
      </el-dialog>
    </div>

    <!-- 分页组件 -->
    <el-pagination
        v-if="filteredUsers.length > 0"
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredUsers.length"
        :page-sizes="[10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { chatSelectMessageList } from '@/api/chat';
import {getUserInfo} from "@/utils/auth.js";
import {userSelectPage} from "@/api/user.js";
import Chat from "@/views/Chat.vue";

const loading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const allUsers = ref([]);
const filteredUsers = ref([]);
const doctorId = getUserInfo().doctorId;
const userId = ref(0);
const dialogVisible = ref(false);
const refreshKey = ref(0);


// 模拟获取所有用户（替换为真实接口）
const fetchAllUsers = async () => {
  try {
    const response = await userSelectPage();
    allUsers.value = response.data.records;
    await filterUsers(); // 过滤用户
  } catch (error) {
    console.error('获取用户失败:', error);
  } finally {
    loading.value = false;
  }
};

// 过滤用户：仅保留realtime接口返回数据不为空的用户
const filterUsers = async () => {
  const promises = allUsers.value.map(async (user) => {
    const res = await chatSelectMessageList({
      senderId: user.userId,
      receiverId: doctorId,
    });
    return res.data; // 返回接口数据
  });

  // 并行请求后过滤用户
  const results = await Promise.all(promises);
  filteredUsers.value = allUsers.value.filter((user, index) => {
    return Array.isArray(results[index]) && results[index].length > 0;
  });
};

// 计算当前页显示的数据
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUsers.value.slice(start, end);
});

// 分页事件处理
const handleSizeChange = () => {
  currentPage.value = 1; // 切换页数时重置到第一页
};

const handleCurrentChange = () => {};

const handlerClick = (id) => {
  dialogVisible.value = true;
  userId.value = id;
  refreshKey.value++;
};

// 初始化加载
onMounted(() => {
  fetchAllUsers();
});
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.loading {
  text-align: center;
  margin: 20px 0;
  color: #409eff;
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.user-card {
  width: 300px; /* 卡片宽度可调整 */
  margin-bottom: 20px;
}

.card-content {
  padding: 15px;
}

.real-name,
.other-field {
  margin-bottom: 8px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
